from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ServerEndpoint
from iClouds.room import roomManager
from iClouds.player import PQOTD

import logging
import datetime
import threading


def beijing(sec, what):
    beijing_time = datetime.datetime.now() + datetime.timedelta(hours=8)
    return beijing_time.timetuple()


logging.Formatter.converter = beijing
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("../logs/tankdb.log")
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)


class QOTDFactory(Factory):
    """协议工厂"""

    size = 5
    rooms = {}

    def __init__(self):
        super().__init__()

    def buildProtocol(self, addr):
        return PQOTD(self)

    def startFactory(self):
        print("Factory is start...")
        logger.info(f"[系统启动] 服务器正在启动...")
        self.rooms["room_0"] = roomManager("房间一")
        self.rooms["room_0"].start()
        self.rooms["room_1"] = roomManager("房间二")
        self.rooms["room_1"].start()

    def stopFactory(self):
        for room in self.rooms.values():
            unit = room.plant
            unit |= room.zombie
            unit |= room.jewelry
            unit |= room.card
            unit |= room.sunlight
            unit |= room.slug
            for i in unit:
                i.stop()
                i.join()
            room.stop()
            room.join()
        print("Factory is stop...")


def ServerManager():
    # print("ServerManager is start...")
    from twisted.internet import reactor

    endpoint = TCP4ServerEndpoint(reactor, 8000)
    endpoint.listen(QOTDFactory())
    reactor.run()


if __name__ == "__main__":
    print("...Hello...")
    ServerManager()
    print("...Bye...")
    print(threading.enumerate())
